using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace StudentVideo.Client.Services;

public class JsInteropService(IJSRuntime jsRuntime): IAsyncDisposable {
   private readonly IJSRuntime _jsRuntime = jsRuntime;
   private IJSObjectReference? _module;

   /// <summary>
   /// 获取元素的属性值
   /// </summary>
   /// <typeparam name="T">值类型</typeparam>
   /// <param name="cssSelect">css 选择器</param>
   /// <param name="propertyName">值名称</param>
   /// <returns></returns>
   public async ValueTask<T> GetElementProperty<T>(string cssSelect, string propertyName) {
      _module ??= await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/elementInterop.js");

      return await _module.InvokeAsync<T>("getElementProperty", cssSelect, propertyName);
   }

   public async ValueTask DisposeAsync() {
      if (_module != null) {
         await _module.DisposeAsync();
      }
   }
}
